import React, { useState } from 'react';
import useLocalStorage from '../hooks/useLocalStorage';
import useCounter from '../hooks/useCounter';
import useFetch from '../hooks/useFetch';
import useToggle from '../hooks/useToggle';

interface User {
  id: number;
  name: string;
  email: string;
}

const CustomHooksDemo: React.FC = () => {
  // useLocalStorage 示例
  const [name, setName] = useLocalStorage<string>('userName', '');
  const [theme, setTheme] = useLocalStorage<string>('theme', 'light');

  // useCounter 示例
  const counter1 = useCounter(0, 1);
  const counter2 = useCounter(10, 5);

  // useFetch 示例
  const [userId, setUserId] = useState(1);
  const { data: user, loading, error } = useFetch<User>(
    `https://jsonplaceholder.typicode.com/users/${userId}`
  );

  // useToggle 示例
  const modalToggle = useToggle(false);
  const sidebarToggle = useToggle(false);

  return (
    <div className="demo-page">
      <h1>自定义 Hooks</h1>
      <p className="description">
        学习如何创建和使用自定义 Hooks，将组件逻辑提取到可重用的函数中
      </p>

      {/* useLocalStorage 示例 */}
      <div className="demo-section">
        <h2>useLocalStorage Hook</h2>
        <p>将状态持久化到 localStorage 的自定义 Hook</p>
        
        <div className="form-group">
          <label>用户名：</label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="输入用户名"
          />
          <p>当前保存的用户名: {name || '未设置'}</p>
        </div>

        <div className="form-group">
          <label>主题：</label>
          <select 
            value={theme} 
            onChange={(e) => setTheme(e.target.value)}
          >
            <option value="light">浅色</option>
            <option value="dark">深色</option>
            <option value="blue">蓝色</option>
          </select>
          <p>当前主题: {theme}</p>
        </div>
      </div>

      {/* useCounter 示例 */}
      <div className="demo-section">
        <h2>useCounter Hook</h2>
        <p>可配置步长的计数器 Hook</p>
        
        <div className="comparison">
          <div className="comparison-item">
            <h3>计数器 1（步长 1）</h3>
            <div className="counter-demo">
              <p>计数: {counter1.count}</p>
              <div className="button-group">
                <button onClick={counter1.decrement}>-</button>
                <button onClick={counter1.increment}>+</button>
                <button onClick={counter1.reset}>重置</button>
              </div>
            </div>
          </div>
          
          <div className="comparison-item">
            <h3>计数器 2（步长 5）</h3>
            <div className="counter-demo">
              <p>计数: {counter2.count}</p>
              <div className="button-group">
                <button onClick={counter2.decrement}>-5</button>
                <button onClick={counter2.increment}>+5</button>
                <button onClick={counter2.reset}>重置</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* useFetch 示例 */}
      <div className="demo-section">
        <h2>useFetch Hook</h2>
        <p>简化数据获取的 Hook</p>
        
        <div className="user-selector">
          <label>选择用户 ID：</label>
          <select 
            value={userId} 
            onChange={(e) => setUserId(Number(e.target.value))}
          >
            {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(id => (
              <option key={id} value={id}>用户 {id}</option>
            ))}
          </select>
        </div>

        {loading && <div className="loading">加载中...</div>}
        {error && <div style={{ color: 'red' }}>错误: {error}</div>}
        
        {user && (
          <div className="user-info">
            <h3>{user.name}</h3>
            <p><strong>邮箱:</strong> {user.email}</p>
            <p><strong>ID:</strong> {user.id}</p>
          </div>
        )}
      </div>

      {/* useToggle 示例 */}
      <div className="demo-section">
        <h2>useToggle Hook</h2>
        <p>简化布尔值切换的 Hook</p>
        
        <div className="button-group">
          <button onClick={modalToggle.toggle}>
            {modalToggle.value ? '隐藏' : '显示'}模态框
          </button>
          <button onClick={sidebarToggle.toggle}>
            {sidebarToggle.value ? '关闭' : '打开'}侧边栏
          </button>
        </div>

        {modalToggle.value && (
          <div className="demo-section" style={{ backgroundColor: '#f8f9fa' }}>
            <h3>模态框内容</h3>
            <p>这是一个通过 useToggle 控制的模态框</p>
            <button onClick={modalToggle.setFalse}>关闭</button>
          </div>
        )}

        {sidebarToggle.value && (
          <div className="demo-section" style={{ backgroundColor: '#e9ecef' }}>
            <h3>侧边栏内容</h3>
            <p>这是一个通过 useToggle 控制的侧边栏</p>
            <button onClick={sidebarToggle.setFalse}>关闭</button>
          </div>
        )}
      </div>

      {/* 创建自定义 Hook 的指南 */}
      <div className="demo-section">
        <h2>创建自定义 Hook 的指南</h2>
        
        <div className="best-practices">
          <div className="practice-item">
            <h3>命名规范</h3>
            <ul>
              <li>必须以 "use" 开头（如 useLocalStorage）</li>
              <li>描述 Hook 的功能（如 useFetch, useToggle）</li>
              <li>避免与现有 Hook 冲突</li>
            </ul>
          </div>

          <div className="practice-item">
            <h3>设计原则</h3>
            <ul>
              <li>单一职责 - 每个 Hook 只做一件事</li>
              <li>可组合 - 可以与其他 Hook 组合使用</li>
              <li>可配置 - 提供合理的默认参数</li>
              <li>可测试 - 易于单元测试</li>
            </ul>
          </div>

          <div className="practice-item">
            <h3>最佳实践</h3>
            <ul>
              <li>使用 useCallback 和 useMemo 优化性能</li>
              <li>正确处理依赖数组</li>
              <li>提供 TypeScript 类型支持</li>
              <li>添加错误处理</li>
              <li>编写清晰的文档和示例</li>
            </ul>
          </div>
        </div>
      </div>

      {/* 代码示例 */}
      <div className="demo-section">
        <h2>自定义 Hook 代码示例</h2>
        
        <div className="code-example">
          <h3>useLocalStorage 实现</h3>
          <pre>{`function useLocalStorage<T>(key: string, initialValue: T) {
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      return initialValue;
    }
  });

  const setValue = (value: T | ((val: T) => T)) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.error(error);
    }
  };

  return [storedValue, setValue] as const;
}`}</pre>
        </div>

        <div className="code-example">
          <h3>useCounter 实现</h3>
          <pre>{`function useCounter(initialValue: number = 0, step: number = 1) {
  const [count, setCount] = useState(initialValue);

  const increment = useCallback(() => {
    setCount(prev => prev + step);
  }, [step]);

  const decrement = useCallback(() => {
    setCount(prev => prev - step);
  }, [step]);

  const reset = useCallback(() => {
    setCount(initialValue);
  }, [initialValue]);

  return { count, increment, decrement, reset };
}`}</pre>
        </div>
      </div>
    </div>
  );
};

export default CustomHooksDemo;